import myAxios from '../myAxios/myAxios.js';
import myArr from '../myAxios/myArr.js';

import { GetSuJiRequire } from './GetSuJiRequire.js';
import { GetWaiXiaoRequire } from './GetWaiXiaoRequire.js';
import { GetJXSRequire } from './GetJXSRequire.js';
import { GetBuyTypeTable } from './getBuyTypeTable.js';
import { GetStockCountTable } from './GetStockCountTable.js';
import { GetNotFinishedCountTable } from './GetNotFinishedCountTable.js';
import { GetDaiRuKuTable } from './GetDaiRuKuTable.js';
import { GetNotClearBuyCountTable } from './GetNotClearBuyCountTable.js';
import { GetPlanedCountTable } from './GetPlanedCountTable.js';
import { GetSuJiOutPut } from './GetSuJiOutPut.js';
import { GetWaiXiaoOutPut } from './GetWaiXiaoOutPut.js';
import { GetWeekPlanedOrReleasedNotPlaned } from './GetWeekPlanedOrReleasedNotPlaned.js';
import { GetSapNotClear } from './GetSapNotClear.js';
import { GetClearDiffence } from './GetClearDiffence.js';
import { GetAvgMonth, GetSapFHL } from './GetAvgMonth.js';
import { GetSafeStockData } from './GetSafeStockData.js';
import { GetSafeStockCJData } from './GetSafeStockCJData.js';


let metCodePropString = '';
// let metCodeParamString = '';
// 最终查询物料号
let metCodeParamList = [];
// 数据库中存的物料号
let metCodeInDatabaseParamList = [];

// 数字转换
let { GetNumber, GetSum, mergeArraysByKeyWithObjects } = myArr;

// const result = mergeArraysByKeyWithObjects(
// 	{ arr: targetArray, key: 'MATNR', targetKey: 'stock' },
// 	{ arr: sourceArray, key: 'Material', sourceKey: 'delivery' }
// );

let targetObj = { arr: [], key: 'MATNR', targetKey: 'KEY' };
let sourceObj = { arr: [], key: 'MATNR', sourceKey: 'KEY' };
let GetDataList2 = async function (metCodeParamString) {
	try {
		// 测试
		test();

		//#region 正式逻辑

		// 1. 获取描述和库存
		const stockCountTable = await GetStockCountTable(metCodeParamString);
		const rowsSS = stockCountTable.filter(row => row.MATNR === 'E0080111L0');

		let orderList = stockCountTable.map(stockRow => {
			return {
				MATNR: stockRow['MATNR'] || "",
				MAKTX: stockRow['MAKTX'] || "",
				LABST: stockRow['LABST'] || 0,
				oriLABST: GetNumber(stockRow['LABST']) || 0,
				NOT_FINISHED_COUNT: 0,
				OUTCOUNT_SUM: 0,
				DIFFERENCE_BETWEEN_STOCK__OUTCOUNT: 0,
				REQUIRE_SUJI: 0,
				REQUIRE_JINGSHU: 0,
				REQUIRE_WAIXIAO: 0,
				RSMNG: stockRow['RSMNG'] || 0,
				REQUIRE_SUM: 0,
				SUM_DIFFERENCE: 0,
				DRK: 0,
				WQCG_ALL: 0,
				PLANED_COUNT: 0,
				OUTCOUNT_SUJI: 0,
				OUTCOUNT_WAIXIAO: 0,
				WEEK_PLANED: 0,
				WEEK_RELEASED_NOT_PLANED: 0,
				SAP_NOT_CLEAR_COUNT: 0,
				CLEAR_DIFFERENCE: 0,
				AVG_MONTH: 0,
				DIFFERENCE_BETWEEN_REQUIRE_MONTH: 0,
				SAFE_STOCK: 0,
				SAFE_STOCK_CJ: 0,
				MATTYPE: "",
				// ... 初始化 Finnal_Data 的其他属性
			};
		});
		// 清掉没有物料号的
		orderList = orderList.filter(item => item.MATNR !== "");
		targetObj = { arr: orderList, key: 'MATNR', targetKey: 'NOT_FINISHED_COUNT' };
		//#region 2. 获取SAP已建订单
		const notFinishedCountTable = await GetNotFinishedCountTable();
		updateArrKey(notFinishedCountTable, 'NOT_FINISHED_COUNT');
		// orderList = orderList.filter(item => item.NOT_FINISHED_COUNT != 0);
		//#endregion

		//#region 3. 待入库数量
		const daiRuKuTable = await GetDaiRuKuTable();
		updateArrKey(daiRuKuTable, 'DRK');
		// orderList = orderList.filter(item => item.DRK != 0);
		//#endregion

		//#region 4. 获取未清采购数量
		const notClearBuyCountData = await GetNotClearBuyCountTable(metCodeParamString);
		updateArrKey(notClearBuyCountData, 'WQCG_ALL');
		// orderList = orderList.filter(item => item.WQCG_ALL != 0);
		//#endregion

		//#region 5. 获取已排产未完成
		let matnrString = orderList.map(item => item.MATNR).join(",");
		const planedData = await GetPlanedCountTable(matnrString);
		updateArrKey(planedData, 'PLANED_COUNT');
		// orderList = orderList.filter(item => item.PLANED_COUNT != 0);
		//#endregion

		//#region 6. 获取塑机出仓
		const suJiOutTable = await GetSuJiOutPut();
		updateArrKey(suJiOutTable, 'OUTCOUNT_SUJI');
		// orderList = orderList.filter(item => item.OUTCOUNT_SUJI != 0);
		//#endregion

		//#region 7. 获取金属出仓和金属需求
		// const JINGSHUD = await GetJinShuOutPut(); // 假设返回 { [matnr]: JINGSHU_DATA }
		// for (const [matnr, jingshuData] of Object.entries(JINGSHUD)) {
		// 	const data = orderList.find(el => el.MATNR === matnr);
		// 	if (data) {
		// 		data.OUTCOUNT_JINGSHU = jingshuData.CHUCANG;
		// 		data.REQUIRE_JINGSHU = parseInt(jingshuData.XUQIU) || 0;
		// 	}
		// }
		//#endregion

		//#region 8. 获取金属未清采购
		// const srmDataJS = await GetSRMDataJSTable();
		// orderList = updateDatas(orderList, srmDataJS, StringWQCG, StringWQCG, true);
		//#endregion

		//#region 9. 获取9900调拨单
		// const table9900 = await GetTable9900(metCodeParamString);
		//#endregion

		//#region 10. 获取外销出仓
		const waiXiaoOutTable = await GetWaiXiaoOutPut();
		updateArrKey(waiXiaoOutTable, 'OUTCOUNT_WAIXIAO');
		// orderList = orderList.filter(item => item.OUTCOUNT_WAIXIAO != 0);
		//#endregion

		//#region 11. 塑机需求 && 外销需求 
		updateArrKey(window.sujiTable, 'REQUIRE_SUJI');
		// orderList = orderList.filter(item => item.REQUIRE_SUJI != 0);
		updateArrKey(window.waixiaoTable, 'REQUIRE_WAIXIAO');
		// orderList = orderList.filter(item => item.REQUIRE_WAIXIAO != 0);
		//#endregion

		//#region 12. 获取本周已排产 
		const weekPlan = await GetWeekPlanedOrReleasedNotPlaned(true);
		updateArrKey(weekPlan, 'WEEK_PLANED');
		// orderList = orderList.filter(item => item.WEEK_PLANED != 0);
		//#endregion

		//#region 13. 获取本周已释放未排产 和 已释放（已释放数量 = 已排产 + 已释放未排产 ）
		const weekReleasedNotPlan = await GetWeekPlanedOrReleasedNotPlaned(false);
		updateArrKey(weekReleasedNotPlan, 'WEEK_RELEASED_NOT_PLANED');
		// orderList = orderList.filter(item => item.WEEK_RELEASED_NOT_PLANED != 0);
		//#endregion

		//#region 14. SAP未清数量
		const sapNotClearTable = await GetSapNotClear();
		updateArrKey(sapNotClearTable, 'SAP_NOT_CLEAR_COUNT');
		// orderList = orderList.filter(item => item.SAP_NOT_CLEAR_COUNT != 0);
		//#endregion


		//#region 15. 毛差异 和 预留
		const clear_DiffenceTable = await GetClearDiffence(metCodeParamString);
		updateArrKey(clear_DiffenceTable, 'CLEAR_DIFFERENCE');
		// orderList = orderList.filter(item => item.CLEAR_DIFFERENCE != 0);

		updateArrKey(clear_DiffenceTable, 'RSMNG');
		// orderList = orderList.filter(item => item.RSMNG != 0);
		//#endregion

		//#region 16. 获取季月均需求
		const avgDic = await GetAvgMonth(metCodeParamString);
		updateArrKey(avgDic, 'AVG_MONTH');
		// orderList = orderList.filter(item => item.AVG_MONTH != 0);
		//#endregion

		//#region 17. 月发货量
		const sapFHL_Table = await GetSapFHL(metCodeParamString);
		updateArrKey(sapFHL_Table, 'DIFFERENCE_BETWEEN_REQUIRE_MONTH');
		// orderList = orderList.filter(item => item.DIFFERENCE_BETWEEN_REQUIRE_MONTH != 0);
		//#endregion           

		//#region 18. 安全库存
		const safeStockTableDatas = await GetSafeStockData(); GetSafeStockCJData;
		updateArrKey(safeStockTableDatas, 'SAFE_STOCK');
		// orderList = orderList.filter(item => item.SAFE_STOCK != 0);
		//#endregion

		//#region 19. 车间安全库存
		const safeStockCJTableDatas = await GetSafeStockCJData();
		updateArrKey(safeStockCJTableDatas, 'SAFE_STOCK_CJ');
		// orderList = orderList.filter(item => item.SAFE_STOCK_CJ != 0);
		//#endregion


		//#region 20. 获取物料号类型
		const typeDatas = await myAxios.get("陈帅廷查询周计划_获取物料号类型", '', 'Q902');
		for (const item of orderList) {
			let data = typeDatas.find(tData => tData.MATNR == item.MATNR);
			item.MATTYPE = data == null ? "" : data.MATTYPE;
		}
		// updateArrKey(safeStockCJTableDatas, 'SAFE_STOCK_CJ');
		orderList = orderList.filter(item => item.MATTYPE);
		//#endregion


		// orderList = orderList.filter(item => item.OUTCOUNT_WAIXIAO != 0);



		// ... 中间许多类似的步骤，获取各种数据并更新 orderList
		// 例如：获取总需求、本周已排产、本周已释放未排产、SAP未清数量、毛差异、季月均需求、月发货量、安全库存、车间安全库存、物料号类型等
		// 这些步骤的模式都是：await 获取一个数据表，然后调用 updateDatas 或类似逻辑更新 orderList
		// 为简洁起见，这里省略这些重复的步骤，您需要根据C#代码逐一实现

		// 关键的最后计算循环
		for (const row of orderList) {
			const matnr = row.MATNR;

			// 紧急欠缺计算 (需要实现 getJJQQ 函数)
			// row.JJQQ = getJJQQ(row.MATNR, suJiOutTable, JINGSHUD, waiXiaoOutTable);

			// 父子物料逻辑 (需要实现 metCodeTable)
			// const fMatcodeRows = metCodeTable.filter(r => r.F_METCODE != null && (r.METCODE === matnr || r.F_METCODE === matnr));
			// if (fMatcodeRows.length > 0) {
			//   ... 实现父子物料数据共享逻辑
			// }

			// 总出仓
			row.OUTCOUNT_SUM = GetSum([
				row.OUTCOUNT_SUJI,
				row.OUTCOUNT_WAIXIAO,
				row.OUTCOUNT_JINGSHU,
				row.RSMNG
			]);

			// 总需求
			row.REQUIRE_SUM = row.REQUIRE_SUJI + GetNumber(row.WQCG); // 假设 WQCG 是字符串

			row.DIFFERENCE_BETWEEN_STOCK__OUTCOUNT = GetNumber(row.LABST) - GetNumber(row.OUTCOUNT_SUM);
			row.DIFFERENCE_BETWEEN_PLANED__OUTCOUNT = (GetNumber(row.PLANED_COUNT) + GetNumber(row.LABST) - GetNumber(row.OUTCOUNT_SUM));
			row.SUM_DIFFERENCE = GetNumber(row.LABST) +
				GetNumber(row.NOT_FINISHED_COUNT) -
				(row.REQUIRE_SUM + GetNumber(row.OUTCOUNT_WAIXIAO) + GetNumber(row.SAFE_STOCK) + GetNumber(row.SAFE_STOCK_CJ)) +
				GetNumber(row.WQCG_ALL);
			row.WEEK_RELEASED = (GetNumber(row.WEEK_PLANED) + GetNumber(row.WEEK_RELEASED_NOT_PLANED));
		}

		let oriDatas = orderList; // 如果需要设置全局变量
		let finalDatas = orderList; // JavaScript中通常直接返回对象数组
		console.log('finalDatas :>> ', finalDatas);
		return finalDatas;
		//#endregion
	} catch (error) {
		console.error('Error processing data:', error);
		throw error;
	}
};

let test = async function () {

	// let a = await GetSuJiRequire();
	// let b = await GetWaiXiaoRequire();
	// let c = await GetJXSRequire();
};

let updateArrKey = function (arr, key) {
	targetObj.targetKey = key;
	sourceObj = { arr: arr, key: 'MATNR', sourceKey: key };
	mergeArraysByKeyWithObjects(targetObj, sourceObj);
};

export {
	GetDataList2,
};
